package com.zeta.demo.es.model.query;

import cn.hutool.core.util.StrUtil;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import lombok.experimental.Accessors;
import org.springframework.data.elasticsearch.core.query.Criteria;

import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 文章 查询参数
 *
 * @author gcc
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = false)
@Schema(description = "文章查询参数")
public class PostQueryDTO implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;


    /** id */
    @Schema(description = "id")
    private Long id;

    /** 文章标题 */
    @Schema(description = "文章标题")
    private String title;

    /** 文章内容 */
    @Schema(description = "文章内容")
    private String content;

    /** 作者名 */
    @Schema(description = "作者名")
    private String author;

    /** 创建时间 */
    @Schema(description = "创建时间")
    private LocalDate createTime;

    /** 发布时间 */
    @Schema(description = "发布时间")
    private LocalDate publishTime;


    /**
     * 构建Es查询条件
     * @return Criteria
     */
    public Criteria buildCriteria() {
        Criteria criteria = new Criteria();
        if (this.id != null) {
            criteria = criteria.and(new Criteria("id").is(this.id.toString()));
        }
        if (StrUtil.isNotBlank(this.title)) {
            criteria = criteria.and(new Criteria("title").contains(this.title));
        }
        if (StrUtil.isNotBlank(this.content)) {
            criteria = criteria.and(new Criteria("content").contains(this.content));
        }
        if (StrUtil.isNotBlank(this.author)) {
            criteria = criteria.and(new Criteria("author").is(this.author));
        }
        // 创建时间查询（模糊匹配年月日）
        if (this.createTime != null) {
            // 获取当天的开始时间和结束时间
            LocalDateTime startOfDay = this.createTime.atStartOfDay();
            LocalDateTime endOfDay = startOfDay.plusDays(1);
            criteria = criteria.and(new Criteria("createTime")
                    .greaterThanEqual(startOfDay)
                    .lessThan(endOfDay)
            );
        }
        // 发布时间查询（模糊匹配年月日）
        if (this.publishTime != null) {
            // 获取当天的开始时间和结束时间
            LocalDateTime startOfDay = this.publishTime.atStartOfDay();
            LocalDateTime endOfDay = startOfDay.plusDays(1);
            criteria = criteria.and(new Criteria("publishTime")
                    .greaterThanEqual(startOfDay)
                    .lessThan(endOfDay)
            );
        }
        return criteria;
    }
}
